import { AsyncStorage } from 'react-native';
import { kAuthorization, kContentType } from "../constant";
import Request from "../utils/Request";
import constant from "../utils/constant";
const { Toast } = require('antd-mobile');
const STORAGE_KEY = "STORAGE_KEY_room";
export default {
    namespace: 'room',
    state: {
        list: null,
        loading: false
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({ payload }, { call, put, select }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *clear({ payload }, { put, select }) {
            const room = yield select(state => state.auth);
            room.list = null;
            yield put({ type: 'save', payload: Object.assign({}, room) });
        },
        *fetchList({ payload }, { put, call, select }) {
            const auth = yield select(state => state.auth);
            const room = yield select(state => state.room);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const result = yield call(Request.get, Request.getApi().roomList, payload);
            if (result) {
                if (payload.loadmore) {
                    const content = room.list.content;
                    room.list = result;
                    room.list.content = content.concat(result.content);
                }
                else {
                    room.list = result;
                }
                yield put({
                    type: 'save',
                    payload: Object.assign({}, room)
                });
            }
        },
        *reserveRoom({ payload }, { call, put, select }) {
            let auth = yield select(state => state.auth);
            payload['params'] = Object.assign({}, payload);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            payload[kContentType] = 'application/json';
            const result = yield call(Request.post, Request.getApi().roomReserve, payload);
            if (result) {
                auth.userInfo.paid = (Number(auth.userInfo.paid) - payload.paid) + '';
                yield put({
                    type: 'save',
                    payload: Object.assign({}, auth)
                });
                Toast.success('您已经成功提交预定请求!!', constant.ToastDuration);
            }
        },
    },
    subscriptions: {
        setup({ dispatch }) {
        }
    },
};
